import { Collection, DatasetListItem, MAX_NAME_LENGTH } from '@/common';
import datasetService from '@/api/services/datasetService';
import { useEffect, useState } from 'react';
import {
  Button,
  Descriptions,
  Dropdown,
  Input,
  MenuProps,
  message,
  Modal,
  Space,
  Spin,
  Splitter,
  Table,
  Tag,
  Typography,
} from 'antd';
import {
  CloseOutlined,
  DeleteOutlined,
  EditOutlined,
  EllipsisOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { SvgIcon } from '@/components/icon';
import dayjs from 'dayjs';
import { useUpdateEffect } from 'react-use';
import { useDebounceFn } from 'ahooks';
import useWindowWidth from '@/hooks/event/use-window-width';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
import EmptyPape from '@/components/empty/EmptyPage';
import { Size } from '@/types/common';
import { useContextSelector } from 'use-context-selector';
import { RoleManageContext } from '../context';
import { ApiDatasetEvent, ApiItem } from '@/types/api';
import React from 'react';
import { Role } from '@/types/role';

const { Text } = Typography;

interface Props {
  selectedItem: Role | undefined;
  isAdmin: boolean;
  isPermit: boolean;
  parentSize: Size;
}
const RoleTable = ({ selectedItem, isAdmin, isPermit, parentSize }: Props) => {
  const [collections, setCollections] = useState<Collection[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchValue, setSearchValue] = useState('');
  const [loading, setLoading] = useState(false);
  const [renameModalVisible, setRenameModalVisible] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [selectedRows, setSelectedRows] = useState<Collection[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [newName, setNewName] = useState('');
  const [isBatchDelete, setIsBatchDelete] = useState(false);
  const [editItem, setEditItem] = useState<Collection | undefined>(undefined);
  const { isPc } = useWindowWidth();
  const [expandedData, setExpandedData] = useState<{ [key: string]: ApiItem }>({});
  const [expandLoading, setExpandLoading] = useState<{ [key: string]: boolean }>({});
  const { event$ } = useContextSelector(RoleManageContext, (s) => s);

  const fetchExpandedData = async (record: Collection) => {
    setExpandLoading((prev) => ({ ...prev, [record._id]: true }));
    // Simulate an API call
    const data = await datasetService.datasetDataV2List({
      collectionId: record._id,
      searchText: '',
      offset: 0,
      pageSize: 15,
    });
    const apiItem = JSON.parse(data.list[0].q) as ApiItem;
    setExpandedData((prev) => ({ ...prev, [record._id]: apiItem }));
    setExpandLoading((prev) => ({ ...prev, [record._id]: false }));
  };

  const parameterList = (apiItem: ApiItem) => {
    const properties = apiItem.function.parameters.properties;
    const required = apiItem.function.parameters.required;
    return (
      <Descriptions
        size="small"
        layout="vertical"
        contentStyle={{ fontSize: '12px', color: '#a3a3a3' }}
        labelStyle={{ fontSize: '12px' }}
        column={4}
      >
        {Object.keys(properties).map((key, index) => (
          <React.Fragment key={`${key}_${index}`}>
            <Descriptions.Item
              label={index === 0 ? '参数名称' : ''}
              labelStyle={index !== 0 ? { display: 'none' } : {}}
            >
              {key}
            </Descriptions.Item>
            <Descriptions.Item
              label={index === 0 ? '参数类型' : ''}
              labelStyle={index !== 0 ? { display: 'none' } : {}}
            >
              {properties[key].type}
            </Descriptions.Item>
            <Descriptions.Item
              label={index === 0 ? '参数说明' : ''}
              labelStyle={index !== 0 ? { display: 'none' } : {}}
            >
              {properties[key].description}
            </Descriptions.Item>
            <Descriptions.Item
              label={index === 0 ? '必须' : ''}
              labelStyle={index !== 0 ? { display: 'none' } : {}}
            >
              {required.includes(key) ? '是' : '否'}
            </Descriptions.Item>
          </React.Fragment>
        ))}
      </Descriptions>
    );
  };

  const getHttpMethodColor = (method: string) => {
    switch (method) {
      case 'get':
        return '#61affe';
      case 'post':
        return '#49cc90';
      case 'put':
        return '#F9D93E';
      case 'delete':
        return '#f93e3e';
      default:
        return '#61affe';
    }
  };

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: Collection[]) => {
      setSelectedRows(selectedRows);
      setSelectedRowKeys(selectedRowKeys);
    },
    selectedRowKeys: selectedRowKeys,
  };

  const columns = [
    {
      // title: <div>全部文档 ({total})</div>,
      title: (
        <div className="flex items-center">
          <span>数据接口</span>
          {!isPc && (
            <Input
              style={{ border: 'none', background: 'transparent', color: '#C9CEE2' }}
              placeholder="搜索..."
              className="ml-4 text-sm"
              value={searchValue}
              prefix={<SearchOutlined style={{ color: '#C9CEE2', marginRight: '10px' }} />}
              onChange={(e) => {
                setSearchValue(e.target.value);
              }}
            />
          )}
        </div>
      ),
      dataIndex: 'fileInfo',
      key: 'fileInfo',
      render: (_, record: Collection) => {
        const { name } = record;
        const arr = name.split(':');
        return (
          <Space size="small" className="w-full">
            <div className="flex-shrink-0 items-center justify-center rounded-lg">
              <SvgIcon color="#33ADFF" className="mb-1 ml-1 mr-1 mt-1" icon="icon-api" size={24} />
            </div>
            <div
              className="min-w-14 rounded-sm text-center"
              style={{ background: getHttpMethodColor(arr[0]), color: '#fff' }}
            >
              <span>{arr[0].toUpperCase()}</span>
            </div>
            <Text
              ellipsis={{ tooltip: arr[1] }}
              className="ml-2"
              style={{ maxWidth: isPc ? `${parentSize.width * 0.5}px` : '100px' }}
            >
              {arr[1]}
            </Text>
          </Space>
        );
      },
      onCell: () => ({ style: { flex: '1' } }),
    },
    {
      title: (
        <div>
          {isPc && (
            <Input
              style={{ border: 'none', background: 'transparent', color: '#C9CEE2' }}
              placeholder="搜索..."
              className="ml-4 text-sm"
              value={searchValue}
              prefix={<SearchOutlined style={{ color: '#C9CEE2', marginRight: '10px' }} />}
              onChange={(e) => {
                setSearchValue(e.target.value);
              }}
            />
          )}
        </div>
      ),
      // width: '60%',
      key: 'action',
      render: (_, record: Collection) => (
        <div className="flex">
          <div className="ml-auto">
            <Space size="small">
              {isPc && (
                <Text ellipsis={{ tooltip: record.updateTime }} style={{ maxWidth: '140px' }}>
                  {dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss')}
                </Text>
              )}
              {isAdmin && (
                <Dropdown
                  menu={{
                    items: [
                      {
                        key: '1',
                        label: '修改名称',
                        onClick: () => {
                          setNewName(record.name);
                          setEditItem(record);
                          setRenameModalVisible(true);
                        },
                      },
                      {
                        key: '2',
                        label: '删除此数据接口',
                        onClick: () => {
                          setEditItem(record);
                          setDeleteModalVisible(true);
                        },
                      },
                    ],
                  }}
                  trigger={isPc ? ['hover'] : ['click']}
                  placement="bottomLeft"
                >
                  <Button
                    type="text"
                    icon={<EllipsisOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                    }}
                  ></Button>
                </Dropdown>
              )}
            </Space>
          </div>
        </div>
      ),
      // onCell: () => ({ style: { width: '300px' } }),
    },
  ];

  const handlePageChange = (page: number, pageSize: number) => {
    setPage(page);
    setPageSize(pageSize);
  };

  const paginationConfig = {
    current: page,
    pageSize: pageSize,
    pageSizeOptions: undefined,
    total: total,
    onChange: handlePageChange,
  };

  const { run } = useDebounceFn(
    async () => {
      await getCollections();
    },
    {
      wait: 300,
    },
  );

  const clearSelections = () => {
    setSelectedRows([]);
    setSelectedRowKeys([]);
  };

  const getCollections = async () => {
    try {
      if (!selectedItem) {
        return;
      }
      const res = await datasetService.collectionList({
        datasetId: selectedItem?._id ?? '',
        pageNum: page,
        pageSize: pageSize,
        parentId: '',
        searchText: searchValue,
      });
      setCollections(res.data);
      setTotal(res.total);
    } catch (error) {
      console.error(error);
    } finally {
      clearSelections();
      setLoading(false);
    }
  };

  const rename = async () => {
    if (!newName) {
      message.error('文档名称不能为空');
      return;
    }
    if (newName.length > MAX_NAME_LENGTH) {
      message.error(`文档名称长度不能超过 ${MAX_NAME_LENGTH} 字符`);
      return;
    }
    if (!editItem) {
      return;
    }
    await datasetService.updateDatasetCollection({
      id: editItem?._id,
      name: newName, // 假设 newName 是新的名称
    });
    message.success('修改名称成功！');
    setRenameModalVisible(false);
    setEditItem(undefined);
    run();
  };

  const handleDeleteConfirm = async () => {
    if (isBatchDelete) {
      const promises = selectedRows.map(async (row) => {
        await datasetService.deleteDatasetCollection(row._id);
      });

      await Promise.all(promises);
    } else {
      if (!editItem) {
        return;
      }
      await datasetService.deleteDatasetCollection(editItem._id);
    }
    message.success('删除成功！');
    setDeleteModalVisible(false);
    setEditItem(undefined);
    setIsBatchDelete(false);
    clearSelections();
    run();
  };

  const handleBatchDelete = async () => {
    setIsBatchDelete(true);
    setDeleteModalVisible(true);
  };

  useEffect(() => {
    setPage(1);
    setPageSize(10);
    setTotal(0);
    if (selectedItem) {
      setLoading(true);
      run();
    } else {
      run();
      setCollections([]);
    }
  }, [selectedItem]);

  useUpdateEffect(() => {
    setLoading(true);
    run();
  }, [page, pageSize]);

  useUpdateEffect(() => {
    setLoading(true);
    setPage(1);
    setPageSize(10);
    run();
  }, [searchValue]);

  event$?.useSubscription((val) => {
    // if (val == ApiDatasetEvent.REFRESHCOLLECTION) {
    //   setLoading(true);
    //   setPage(1);
    //   setPageSize(10);
    //   setTotal(0);
    //   setSearchValue('');
    //   run();
    // }
  });

  return (
    <>
      <Table
        rowClassName="bg-[#F5F7FB] custom-scrollbar"
        className="custom-scrollbar"
        loading={loading}
        dataSource={collections}
        columns={columns}
        pagination={paginationConfig}
        rowSelection={isAdmin ? rowSelection : {}}
        rowKey={'id'}
        locale={{
          emptyText: (
            <div className="h-full" style={{ textAlign: 'center', color: '#999' }}>
              {!loading && <EmptyPape description="暂无数据" />}
            </div>
          ),
        }}
      ></Table>

      {selectedRows.length > 0 && isAdmin && (
        <div
          className="animated-div"
          style={{
            position: 'fixed',
            bottom: '5%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: '#474C5F',
            borderRadius: '50px',
          }}
        >
          <Space className="ml-2 mr-2" style={{ height: '45px' }}>
            <Button
              style={{ color: '#fff' }}
              type="text"
              icon={<CloseOutlined />}
              onClick={clearSelections}
            ></Button>
            <span className="whitespace-nowrap text-nowrap text-xs" style={{ color: '#8E93A4' }}>
              已选 {selectedRows.length} 项
            </span>
            <Splitter />

            <Button style={{ color: '#fff' }} type="text" onClick={handleBatchDelete}>
              删除
            </Button>
          </Space>
        </div>
      )}

      <Modal
        title={<div style={{ textAlign: 'center', width: '100%' }}>重命名</div>}
        open={renameModalVisible}
        onCancel={() => {
          setRenameModalVisible(false);
        }}
        okText="确定"
        cancelText="取消"
        closable={false}
        width={300}
        centered
        footer={
          <div style={{ textAlign: 'center' }}>
            <Space size={56}>
              <Button
                onClick={() => {
                  setRenameModalVisible(false);
                }}
              >
                取消
              </Button>
              <Button type="primary" onClick={rename}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '60px',
          }}
        >
          <Input value={newName} onChange={(e) => setNewName(e.target.value)} />
        </div>
      </Modal>

      <DeleteConfirmModal
        visible={deleteModalVisible}
        text={`确定要删除吗？`}
        onCancel={() => {
          setDeleteModalVisible(false);
        }}
        onConfirm={handleDeleteConfirm}
      />
    </>
  );
};

export default RoleTable;
